import { Injectable } from '@angular/core';
import {Platform, ToastController, App, NavController, Tabs, ViewController} from 'ionic-angular';

@Injectable()
export class BackButtonService {

  //控制硬件返回按钮是否触发，默认false
  backButtonPressed: boolean = false;

  //构造函数 依赖注入
  constructor(public platform: Platform,
              public appCtrl: App,
              public toastCtrl: ToastController) { }

  //注册方法
  registerBackButtonAction(tabRef: Tabs): void {
    console.log("registerBackButtonAction:注册返回");
    //registerBackButtonAction是系统自带的方法
    this.platform.registerBackButtonAction(() => {
      //获取NavController
      let activeNav: NavController = this.appCtrl.getActiveNav();
      let activeView: ViewController = activeNav.getActive();
      //如果当前的view为第一个且是overlay，则dismiss（代表modal中的第一个）
      if (activeView.index === 0 && activeView.isOverlay === true) {
        //alert("activeNav.id:"+activeNav.id+" activeView.zIndex:"+activeView.getZIndex());
        activeView.dismiss().catch(() => {alert("dismiss failed!")});
      } else {
        //如果nav可以返回上一页，则执行pop
        if (activeNav.canGoBack()) {
          //alert("返回上一页!");
          console.log("goback返回上一页");
          activeNav.pop();
        } else {
          if (tabRef == null || tabRef._selectHistory[tabRef._selectHistory.length - 1] === tabRef.getByIndex(0).id) {
            //执行退出
            //alert("准备推出!");
            console.log("开始执行退出...");
            this.showExit();
          } else {
            console.log("选择首页的第一个标签");
            //选择首页第一个的标签
            tabRef.select(0);
          }
        }
      }

    });
  }

  //退出应用方法
  private showExit(): void {
    //如果为true，退出
    if (this.backButtonPressed) {
      this.platform.exitApp();
    } else {
      //第一次按，弹出Toast
      this.toastCtrl.create({
        message: '再按一次退出应用',
        duration: 2000,
        position: 'top'
      }).present();
      //标记为true
      this.backButtonPressed = true;
      //两秒后标记为false，如果退出的话，就不会执行了
      setTimeout(() => this.backButtonPressed = false, 2000);
    }
  }
}
